<script lang="ts" setup>
import type { SystemOAuth2ClientApi } from '#/api/system/oauth2/client';

import { computed, defineEmits, onMounted, ref } from 'vue';

import { Search } from '@vben/icons';
import { usePreferences } from '@vben/preferences';

import { Input, List } from 'ant-design-vue';

import { getOAuth2ClientList } from '#/api/system/oauth2/client';

const emit = defineEmits(['select']);
const { isDark } = usePreferences();

const appList = ref<SystemOAuth2ClientApi.OAuth2Client[]>([]); // 所有应用数据

const searchValue = ref(''); // 搜索输入值

const loading = ref(false);

const selectedAppId = ref<null | number>(null); // 当前选中的应用 ID

/** 根据搜索关键词实时过滤应用列表 */
const filteredList = computed(() => {
  const value = searchValue.value.trim().toLowerCase();
  return value
    ? appList.value.filter((item) => item.name.toLowerCase().includes(value))
    : appList.value;
});

/** 搜索框触发变化 */
function handleSearch(e: any) {
  searchValue.value = e.target.value;
}

/** 选中某个应用后更新状态并通知父组件 */
const handleSelect = (app: SystemOAuth2ClientApi.OAuth2Client) => {
  selectedAppId.value = app.id;
  emit('select', app);
};

/** 加载应用列表并默认选中第一个应用 */
const loadAppList = async () => {
  try {
    loading.value = true;
    const data = await getOAuth2ClientList();
    appList.value = data;
    if (data.length > 0) {
      selectedAppId.value = data[0].id as number;
      emit('select', data[0]); // 默认选中第一个应用
    }
  } catch (error) {
    console.error('获取应用数据失败', error);
  } finally {
    loading.value = false;
  }
};

/** 页面挂载完成后加载应用列表 */
onMounted(() => {
  loadAppList();
});
</script>
<template>
  <div>
    <!-- 顶部操作区域：搜索 + 新增按钮 -->
    <div class="mb-3 flex items-center justify-between gap-2">
      <!-- 搜索框 -->
      <Input
        placeholder="搜索应用"
        allow-clear
        v-model:value="searchValue"
        @change="handleSearch"
        class="w-64"
      >
        <template #prefix>
          <Search class="size-4" />
        </template>
      </Input>
    </div>

    <!-- 应用列表 -->

    <List :data-source="filteredList" :loading="loading" :split="false">
      <template #renderItem="{ item }">
        <List.Item
          class="cursor-pointer px-1"
          :class="{
            'bg-blue-50': selectedAppId === item.id && !isDark,
            'bg-gray-800': selectedAppId === item.id && isDark,
            'hover:bg-gray-50': !isDark,
            'hover:bg-gray-800': isDark,
          }"
          @click="handleSelect(item)"
        >
          <!-- 每项的布局：名称 + 操作菜单 -->
          <div class="flex w-full items-center justify-between">
            <!-- 应用名 -->
            <span>{{ item.name }}</span>
          </div>
        </List.Item>
      </template>
    </List>
  </div>
  <!-- 空数据提示 -->
  <div
    v-if="!loading && filteredList.length === 0"
    class="py-4 text-center text-gray-500"
  >
    暂无数据
  </div>
</template>
